package com.druid.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.druid.common.mapstruct.AdminUserMapstruct;
import com.druid.entity.CeUser;
import com.druid.model.PageBody;
import com.druid.model.ResponseData;
import com.druid.request.AdminUserParam;
import com.druid.request.RequestParamInterfaceGroup;
import com.druid.response.AdminUserVm;
import com.druid.service.managementservice.ICeUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author druid-elf
 * @since 2019-12-23
 */
@SuppressWarnings("unchecked")
@Api(tags={"用户表前端控制器"})
@RestController
@RequestMapping("/ceUser")
@RequiredArgsConstructor
public class CeUserController {

    private final ICeUserService iCeUserService;
    private final AdminUserMapstruct adminUserMapstruct;

    @ApiOperation("得到用户表分页列表")
    @PostMapping(value = "getCeUserList")
    public ResponseData<PageBody<AdminUserVm>> getCeUserList(@RequestBody @Validated AdminUserParam adminUserParam ) {

        LambdaQueryWrapper<CeUser> ceUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ceUserLambdaQueryWrapper.orderByAsc(CeUser::getRoleId,CeUser::getId);

        //  获取分页信息并将其列表属性进行字段映射返给视图层
        IPage<CeUser> page = iCeUserService.page(new Page<>(adminUserParam.getPageNum(), adminUserParam.getPageSize()), ceUserLambdaQueryWrapper);
        List<AdminUserVm> adminUserTransformLList = adminUserMapstruct.AdminUserTransformLList(page.getRecords());
        return ResponseData.SUCCESS(
                PageBody.dealWithList( page, adminUserTransformLList )
        );
    }

    @ApiOperation("根据用户名或者用户id获取用户信息")
    @GetMapping(value = "getUserInfoByUserParam")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "用户名称",value = "username", dataType = "String", example = "德鲁伊", paramType = "query"),
            @ApiImplicitParam(name = "用户id",value = "userId", dataType = "Integer", example = "1", paramType = "query")
    })
    public ResponseData<?> getUserInfoByUserParam(
            @RequestParam(name = "username",required = false) String username,
            @RequestParam(name = "userId",required = false) Integer userId
    ) {

        if (Objects.isNull(username) && Objects.isNull(userId)) return ResponseData.FAILURE("用户名称和用户id至少需要一个");

        LambdaQueryWrapper<CeUser> ceUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(username)) ceUserLambdaQueryWrapper.eq(CeUser::getUsername,username);
        if (Objects.nonNull(userId)) ceUserLambdaQueryWrapper.eq(CeUser::getId,userId);

        return ResponseData.SUCCESS(
                iCeUserService.getOne(ceUserLambdaQueryWrapper)
        );
    }

    @ApiOperation("新增管理员")
    @PostMapping(value = "addAdminUser")
    public ResponseData<String> addAdminUser(@RequestBody @Validated(RequestParamInterfaceGroup.InsertGroup.class) AdminUserParam adminUserParam ) {

       return iCeUserService.save(
               CeUser.builder()
                       .employeeUuid(UUID.randomUUID().toString())
                       .username( adminUserParam.getUsername() )
                       .password( new BCryptPasswordEncoder().encode( adminUserParam.getPassword() ) )
                       .email( adminUserParam.getEmail() )
                       .roleId( adminUserParam.getRoleId() )
                       .status( adminUserParam.getStatus() )
                       .addTime( LocalDateTime.now() )
                       .build()
       )
               ? ResponseData.SUCCESS("添加成功")
               : ResponseData.FAILURE("添加失败");
    }


    @ApiOperation("删除管理员")
    @PostMapping(value = "deleteAdminUser")
    public ResponseData<String> deleteAdminUser(@RequestBody @Validated(RequestParamInterfaceGroup.DeleteGroup.class) AdminUserParam adminUserParam ) {

        return iCeUserService.removeById(adminUserParam.getId())
                ? ResponseData.SUCCESS("删除成功")
                : ResponseData.FAILURE("删除失败");
    }


    @ApiOperation("管理员状态管理")
    @PostMapping(value = "handleAdminUserStatus")
    public ResponseData<String> handleAdminUserStatus( @RequestBody @Validated(RequestParamInterfaceGroup.UpdateGroupSomeOne.class) AdminUserParam adminUserParam ) {

        return iCeUserService.updateById(
                CeUser.builder()
                        .id(adminUserParam.getId())
                        .status(adminUserParam.getStatus())
                        .build()
        )
                ? ResponseData.SUCCESS("操作成功")
                : ResponseData.FAILURE("操作失败");
    }

    @ApiOperation("获取已登入的用户信息")
    @GetMapping(value = "getLoginUserInfo")
    public ResponseData<CeUser> getLoginUserInfo() {

        //  从session缓存中获取用户名称
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = ((UserDetails) principal).getUsername();

        //  数据库拿到用户名称
        CeUser ceUser = iCeUserService.getOne(new LambdaQueryWrapper<CeUser>().eq(CeUser::getUsername, username));
        return ResponseData.SUCCESS(ceUser);
    }

}
